﻿using FluentData;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using SYS.Common;
using SYS.Web.Models;
using System.Net;
using System.Globalization;
using SYS.Web.Function;
namespace SYS.Web.Controllers
{
    public class TaoBaoController : Controller
    {
        //
        // GET: /TaoBao/

        public Page currentPage = new Page();
        public ActionResult Index(string site, string kid)
        {
            currentPage.site = siteConfig.CurrentSite;
            IDbContext dbContext = new DbContext().ConnectionString(currentPage.site.DBConString, currentPage.site.DbProvider);
            int keyindex = 1;
            int.TryParse(site.CharToInt(currentPage.site.CharArray), out keyindex);
            Models.tbk_KeywordBySeed m = dbContext.Sql("select * from tbk_KeywordBySeed where Kid=" + keyindex).QuerySingle<Models.tbk_KeywordBySeed>();
            string key = "";
            if (m != null)
            {
                key = m.Keyword;
            }
            if (key=="")
            {
                throw new Exception("传入的kid未能找到对应关键字");
            }

            currentPage.Key = key;
            currentPage.PageUrl = m.GetKeyPageUrl();
            currentPage.keyword = m;
            dbContext.Dispose();
            this.GetItems(keyindex, key, 1);
            string[] sData = m.GetSuggestData();
            currentPage.Title = currentPage.site.SiteTitle.Replace("{key}", currentPage.Key);
            currentPage.Keywords = currentPage.Title + "|" + currentPage.site.SiteName;
            currentPage.Description = "我们为您找到了相关商品{0}个,你还可查看相关商品{1}";
            for (int i = 0; i < currentPage.site.SuggestDataAmount; i++)
            {
                currentPage.Title = currentPage.Title.Replace("{key"+i+"}",i>=sData.Length?"":sData[i]);
            }
            currentPage.GetRelateData();
            this.ViewData["currentPage"] = currentPage;
            return View();
        }
        /// <summary>
        /// 获取商品和相关数据
        /// </summary>
        /// <param name="kid"></param>
        /// <param name="key"></param>
        /// <param name="page"></param>
        private void GetItems(int kid, string key, int page)
        {
            DateTime now = DateTime.Now;
            IDbContext dbContext = new DbContext().ConnectionString(currentPage.site.DBConString, currentPage.site.DbProvider);
            //去数据库里面的数据
            //取相关
            List<tbk_KeywordBySeed> link_suggestData = dbContext.Sql("SELECT top 20 tkb.* FROM dbo.Kid_Kid kk INNER JOIN dbo.tbk_KeywordBySeed tkb ON kk.RelateKid=tkb.kid WHERE kk.Kid=" + kid).QueryMany<tbk_KeywordBySeed>();
            if (link_suggestData != null && link_suggestData.Count > 0)
            {
                currentPage.suggestData= link_suggestData;
            }
            //取商品
            List<TBItem> items = dbContext.Sql("SELECT  t.* FROM dbo.Kid_Item ki INNER JOIN dbo.TBItem t ON ki.Itemid = t.ItemId WHERE ki.Kid=" + kid).QueryMany<TBItem>();
            if (items != null && items.Count > 0)
            {
                currentPage.tbItems = items;
                return;
            }
            items.Clear();
            List<string> link_suggest = new List<string>();
            Function.GetData.FromTBByKeyword(key, 1, items, link_suggest);
            currentPage.tbItems = items;
            //保存关键字商品关系
            for (int i = 0; i < items.Count; i++)
            {
                var item = items[i];
                var item1 = dbContext.Sql("select * from TBItem where ItemId='" + item.ItemId + "'").QuerySingle<TBItem>();
                if (item1 == null)
                {
                    try
                    {
                        dbContext.Insert<TBItem>("TBItem", item).AutoMap().Execute();
                    }
                    catch {
                        throw new Exception(item.name+"=="+item.ItemId+"=="+item.dealing+"=="+item.comment
                            +"=="+item.fee);
                    } 
                }
                string sql = string.Format("select * from Kid_Item where kid={0} and ItemId='{1}'", kid, item.ItemId);
                Kid_Item kiditem = dbContext.Sql(sql).QuerySingle<Kid_Item>();
                if (kiditem == null)
                {
                    kiditem = new Kid_Item();
                    kiditem.Itemid = item.ItemId;
                    kiditem.Kid = kid;
                    kiditem.ModifyDate = now;
                    dbContext.Insert<Kid_Item>("Kid_Item", kiditem).AutoMap().Execute();
                }
            }
            //保存关键字 关键字关系
            link_suggestData = new List<tbk_KeywordBySeed>();

            for (int i = 0; i < link_suggest.Count; i++)
            {
                int newKid = 0;
                tbk_KeywordBySeed kbs = dbContext.Sql(string.Format("select * from tbk_KeywordBySeed where keyword='{0}'", link_suggest[i])).QuerySingle<tbk_KeywordBySeed>();
                if (kbs == null)
                {
                    kbs = new tbk_KeywordBySeed();
                    kbs.Keyword = link_suggest[i];
                    kbs.Kid=newKid = dbContext.Insert<tbk_KeywordBySeed>("tbk_KeywordBySeed", kbs).AutoMap(d => d.Kid).ExecuteReturnLastId<int>();
                }
                else
                {
                    Kid_Kid kk = dbContext.Sql(string.Format("select * from Kid_Kid where kid={0} and RelateKid={1}", kid, kbs.Kid)).QuerySingle<Kid_Kid>();
                    if (kk == null)
                    {
                        newKid = kbs.Kid;
                    }
                }
                if (newKid > 0)
                {
                    Kid_Kid kk = new Kid_Kid();
                    kk.Kid = kid;
                    kk.RelateKid = newKid;
                    kk.ModifyDate = now;
                    dbContext.Insert<Kid_Kid>("Kid_Kid", kk).AutoMap().Execute();
                }
                link_suggestData.Add(kbs);
            }
            currentPage.suggestData = link_suggestData;
        }
        /// <summary>
        /// 响应跳转页面
        /// </summary>
        /// <returns></returns>
        public ActionResult g(string itemid) {
            ViewBag.Title = itemid;
            return View();
        }
        /// <summary>
        /// 响应搜索页面
        /// </summary>
        /// <returns></returns>
        public ActionResult s(string keyword) {
            keyword=Server.UrlDecode(keyword);
            ViewBag.Title = keyword;
            this.GetItems(0,keyword,1);
            return View();
        }
    }
}
